﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;

namespace Magento.Generation
{
    class Controller : Abstract
    {
        public bool readAndCreate(string dir, string route)
        {
            if (!Directory.Exists(dir))
            {
                this.addMessage(dir + " Directory not exist.");
                return false;
            }

            string module_name = this.getModuleName(dir);
            if (module_name == null)
                return false;
            
            string[] files = Directory.GetFiles(dir, "routes.xml", SearchOption.AllDirectories);

            if (files.Length == 0)
            {
                this.addMessage("routes.xml file not exist.");
                return false;
            }

            foreach (string file in files)
            {
                if (!this.createFileForXml(dir, module_name, file, route))
                {
                    return false;
                }
            }

            return true;
        }

        protected bool createFileForXml(string dir, string module_name, string path, string route)
        {
            XmlDocument doc = new XmlDocument();
            XmlElement element;
            doc.Load(path);
            XmlNamespaceManager nsp = new XmlNamespaceManager(doc.NameTable);
            nsp.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

            bool isAdmin = false;

            if (((XmlElement)doc.SelectSingleNode(@"//config/router")).GetAttribute("id").ToString() == "admin") {
                isAdmin = true;
            }
            var phpClassPrefix = module_name.Replace("_", @"\");
            var phpClassList = new List<String>();
            phpClassList.Add("Controller");
            if (isAdmin)
            {
                phpClassList.Add("Adminhtml");
            }
            

            var routes = route.Split('/').ToList<String>();

            foreach (XmlNode _node in doc.SelectNodes(@"//config/router/route"))
            {
                element = (XmlElement)_node;
                var frontName = element.GetAttribute("frontName").ToString();
                var _routes = new List<String>();

                if (frontName == routes[0]) {
                    for (var i = 1; i < routes.Count(); i++) {
                        _routes.Add(routes[i].Substring(0, 1).ToUpper()+ routes[i].Substring(1));
                    }
                }
                var _phpClassSuffix = String.Join(@"\", phpClassList) + @"\" + String.Join(@"\", _routes);

                var _filePath = Path.Combine(dir, _phpClassSuffix + ".php");
                var php = new PHP();
                if (isAdmin)
                {
                    php.setFullClassName(phpClassPrefix + @"\" + _phpClassSuffix).setExtends(@"Magento\Backend\App\Action");
                    var content = new List<String>();
                    content.Add("    public function execute()");
                    content.Add("    {");
                    content.Add("        $resultRedirect = $this->resultRedirectFactory->create();");
                    content.Add("        return $resultRedirect->setPath('/');");
                    content.Add("    }");
                    php.setMethod(content);
                }
                else {
                    php.setFullClassName(phpClassPrefix + @"\" + _phpClassSuffix).setExtends(@"Magento\Framework\App\Action\Action");
                    var content = new List<String>();
                    content.Add("    public function execute()");
                    content.Add("    {");
                    content.Add("        $resultRedirect = $this->resultRedirectFactory->create();");
                    content.Add("        return $resultRedirect->setPath('/');");
                    content.Add("    }");
                    php.setMethod(content);
                }
                if (php.toFile(_filePath))
                {
                    this.addMessage($"{_filePath} created");
                }
            }
            return true;
        }
    }
}